package com.yiji.fintech.musfinance.common.factory.listenner;

import com.google.common.collect.Maps;
import com.yiji.fintech.musfinance.common.annotation.ListenerAnnotation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider;
import org.springframework.core.type.filter.AnnotationTypeFilter;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.Set;

/**
 * 加载所有监听器到缓存
 * Created by ouwen@yiji.com} on 2017/9/13.
 */
@Component
@Slf4j
public class ListennerLoadFactory implements ApplicationContextAware, InitializingBean {

    private String scanBasePath = "com.yiji.fintech.musfinance";
    private ApplicationContext applicationContext;
    private  Map<String,Class> listennerMap = null;

    @Override
    public void afterPropertiesSet() throws Exception {
        listennerMap = Maps.newConcurrentMap();
        scanListener();
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    /**
     * 扫描监听器注解类
     */
    private void scanListener(){
        ClassPathScanningCandidateComponentProvider provider =
                new ClassPathScanningCandidateComponentProvider(false);
        provider.addIncludeFilter(new AnnotationTypeFilter(ListenerAnnotation.class));
        Set<BeanDefinition> components = provider.findCandidateComponents(scanBasePath);
        for (BeanDefinition component : components) {
            try {
                Class lister = Class.forName(component.getBeanClassName());
                ListenerAnnotation annotation = (ListenerAnnotation)lister.getAnnotation(ListenerAnnotation.class);
                listennerMap.put(annotation.value(),lister);
            } catch (ClassNotFoundException e) {
                log.error("扫描监听器类反射异常【{}】",e.getMessage());
            }catch (Exception e){
                log.error("扫描监听器类异常【{}】",e.getMessage());
            }
        }
    }
    public Map<String, Class> getListennerMap() {
        return listennerMap;
    }
}
